import type { BaseResponse, PageData, PageResponse } from '../types/response';
import { getErrorMessage } from './errorCode';

/**
 * API接口URL配置
 */
export const API_CONFIG = {
  // 生产环境URL
  baseUrl: 'https://www.gdutlife.cn:12000',
  // 测试环境URL
  testUrl: 'https://4fo38gy44684.vicp.fun'
};

/**
 * 当前使用的API基础URL
 * 开发者手动修改：使用 API_CONFIG.baseUrl 或 API_CONFIG.testUrl
 */
export const BASE_URL = API_CONFIG.baseUrl;

/**
 * HTTP请求方法枚举
 */
export enum HttpMethod {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
  DELETE = 'DELETE'
}

/**
 * HTTP请求配置接口
 */
interface RequestOptions {
  url: string;
  method: HttpMethod;
  data?: any;
  params?: Record<string, any>;
  header?: Record<string, string>;
  timeout?: number;
  showError?: boolean; // 是否显示错误提示
}

/**
 * 处理请求URL
 * @param url 请求路径
 * @returns 完整的请求URL
 */
const handleUrl = (url: string): string => {
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  return `${BASE_URL}${url.startsWith('/') ? url : `/${url}`}`;
};

/**
 * 处理请求错误
 * @param error 错误信息
 */
const handleError = (error: any) => {
  console.error('请求错误详情:', error);
  
  let errorMessage = '网络请求失败，请稍后重试';
  
  // 根据错误类型提供更具体的错误信息
  if (error.errMsg) {
    if (error.errMsg.includes('timeout')) {
      errorMessage = '请求超时，请检查网络连接';
    } else if (error.errMsg.includes('fail')) {
      errorMessage = '网络连接失败，请检查网络设置';
    } else if (error.errMsg.includes('ssl')) {
      errorMessage = 'SSL连接失败，请检查证书配置';
    }
  }
  
  uni.showToast({
    title: errorMessage,
    icon: 'none',
    duration: 3000
  });
  return Promise.reject(error);
};

/**
 * 发送HTTP请求
 * @param options 请求配置
 * @returns Promise
 */
export const request = <T>(options: RequestOptions): Promise<BaseResponse<T>> => {
  const { url, method, data, params, header = {}, timeout = 15000, showError = true } = options;

  // 构建完整URL
  let fullUrl = handleUrl(url);
  
  // 处理GET请求参数
  if (method === HttpMethod.GET && params) {
    const queryString = Object.entries(params)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
      .join('&');
    fullUrl += fullUrl.includes('?') ? `&${queryString}` : `?${queryString}`;
  }

  // 请求头设置
  const headers = {
    'Content-Type': 'application/json',
    ...header
  };

  return new Promise((resolve, reject) => {
    console.log('发送请求:', {
      url: fullUrl,
      method: method,
      data: method === HttpMethod.GET ? undefined : data,
      headers: headers
    });
    
    uni.request({
      url: fullUrl,
      method: method,
      data: method === HttpMethod.GET ? undefined : data,
      header: headers,
      timeout,
      // 添加SSL验证跳过（仅用于调试，生产环境应该移除）
      sslVerify: false,
      success: (res) => {
        console.log('请求成功响应:', res);
        const response = res.data as BaseResponse<T>;
        
        // 请求成功但业务逻辑错误
        if (response.code !== 0) {
          if (showError) {
            // 使用错误码映射获取错误信息
            const errorMsg = getErrorMessage(response.code, response.msg || '请求失败');
            uni.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 2000
            });
          }
          reject(response);
          return;
        }
        
        resolve(response);
      },
      fail: (err) => {
        console.error('请求失败:', err);
        handleError(err);
        reject(err);
      }
    });
  });
};

/**
 * GET请求
 * @param url 请求路径
 * @param params 请求参数
 * @param header 请求头
 * @param showError 是否显示错误提示
 * @returns Promise
 */
export const get = <T>(url: string, params?: Record<string, any>, header?: Record<string, string>, showError = true): Promise<BaseResponse<T>> => {
  return request<T>({
    url,
    method: HttpMethod.GET,
    params,
    header,
    showError
  });
};

/**
 * POST请求
 * @param url 请求路径
 * @param data 请求数据
 * @param header 请求头
 * @param showError 是否显示错误提示
 * @returns Promise
 */
export const post = <T>(url: string, data?: any, header?: Record<string, string>, showError = true): Promise<BaseResponse<T>> => {
  return request<T>({
    url,
    method: HttpMethod.POST,
    data,
    header,
    showError
  });
};

/**
 * PUT请求
 * @param url 请求路径
 * @param data 请求数据
 * @param header 请求头
 * @param showError 是否显示错误提示
 * @returns Promise
 */
export const put = <T>(url: string, data?: any, header?: Record<string, string>, showError = true): Promise<BaseResponse<T>> => {
  return request<T>({
    url,
    method: HttpMethod.PUT,
    data,
    header,
    showError
  });
};

/**
 * DELETE请求
 * @param url 请求路径
 * @param data 请求数据
 * @param header 请求头
 * @param showError 是否显示错误提示
 * @returns Promise
 */
export const del = <T>(url: string, data?: any, header?: Record<string, string>, showError = true): Promise<BaseResponse<T>> => {
  return request<T>({
    url,
    method: HttpMethod.DELETE,
    data,
    header,
    showError
  });
};

/**
 * 分页请求
 * @param url 请求路径
 * @param params 请求参数
 * @param header 请求头
 * @param showError 是否显示错误提示
 * @returns Promise
 */
export const getPage = <T>(url: string, params?: Record<string, any>, header?: Record<string, string>, showError = true): Promise<PageResponse<T>> => {
  return request<PageData<T>>({
    url,
    method: HttpMethod.GET,
    params,
    header,
    showError
  }) as Promise<PageResponse<T>>;
}; 